# 对话结束后的整体分析
from sqlalchemy import select
from sqlalchemy.orm import Session

from models import engine, Chat, Message
from schemas.common import MessageAnalysisReport


def get_messages_and_analyses(chat_id: str) -> list[MessageAnalysisReport]:
    reports: list[MessageAnalysisReport] = []

    with Session(engine) as session:
        chat = session.get(Chat, chat_id)
        if not chat:
            raise Exception(f"Chat with id {chat_id} does not exist")

        # 获取所有消息
        stmt = select(Message).where(Message.chat_id == chat_id).order_by(Message.index)
        messages = session.scalars(stmt)

        # 获取消息分析
        for message in messages:
            analysis = message.analysis
            if analysis is not None:
                reports.append(
                    MessageAnalysisReport(
                        index=message.index,
                        role=message.role,
                        content=message.content,
                        grammar_analysis=analysis.grammar_analysis,
                        pronunciation_analysis=analysis.pronunciation_analysis,
                    )
                )
            else:
                reports.append(
                    MessageAnalysisReport(
                        index=message.index,
                        role=message.role,
                        content=message.content,
                        grammar_analysis=None,
                        pronunciation_analysis=None,
                    )
                )

    return reports
